from openai import OpenAI

import jsonReader
import chatbot.messageList

class StreamResponser:
    def __init__(self, defaultSetting, characterName):
        """
        初始化 StreamResponser 对象。

        参数:
        defaultSetting (str): 系统默认设置消息。
        """
        # 读取 API 凭证
        api_credentials = jsonReader.JsonFileReader('./resource/api-key.json').read_json_file()
        if api_credentials:
            self.client = OpenAI(
                api_key=api_credentials['apiKey'],
                base_url=api_credentials['baseUrl']
            )
        else:
            raise ValueError("API credentials not found or invalid.")

        # 初始化 MessageContent 类
        self.messageList = chatbot.messageList.MessageContent(defaultSetting)
        self.characterName = characterName

    def next(self, content):
        """
        发送用户消息并获取流式响应。

        参数:
        content (str): 用户发送的消息内容
        """
        # 添加用户消息到消息列表
        self.messageList.addMessage('user', content)

        # 获取流式响应
        response = self.client.chat.completions.create(
            model="glm-4",
            messages=self.messageList.getMessageList(),
            top_p=0.7,
            temperature=0.9,
            stream=True
        )

        fullMessage = ''
        for chunk in response:
            if chunk.choices:
                choice = chunk.choices[0]
                if choice.delta and choice.delta.content:
                    fullMessage += choice.delta.content

        # 添加AI消息到消息列表
        self.messageList.addMessage('assistant', fullMessage)
        return self

    def speak(self):
        '''
        展示最后一条消息
        '''
        print(f'你的{self.characterName}说：{self.messageList.getLastMessage()}')
